﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AssetsSys.BLL.AutoMapper;
using AssetsSys.DAL;
using AssetsSys.Dto.Assets;
using AssetsSys.Dto.Source;
using AssetsSys.model;

namespace AssetsSys.BLL
{
    /// <summary>
    /// 资产来源
    /// </summary>
    public class SourcesManger
    {
        /// <summary>
        /// 资产来源列表
        /// </summary>
        /// <returns></returns>
        public static async Task<List<SourceModel>> GetList()
        {
            using (var souSvc = new SourcesService())
            {
                var sources = await souSvc.GetAll().OrderByDescending(x => x.CreateTime).ToListAsync();
                return sources.MapTo<List<SourceModel>>();
            }
        }

        /// <summary>
        /// 添加来源
        /// </summary>
        /// <param name="sourceName"></param>
        /// <returns></returns>
        public static async Task<bool> Create(string sourceName)
        {
            using (var souSvc = new SourcesService())
            {
               await souSvc.CreateAsync(new Source()
               {
                   SourceName = sourceName
               });
                return true;
            }
        }

        /// <summary>
        /// 删除来源
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<bool> Delete(Guid id)
        {
            using (var souSvc = new SourcesService())
            {
                var model = await souSvc.GetOne(id);
                if (model == null)
                {
                    return false;
                }
                await souSvc.Remove(id);
                return true;
            }
        }

        /// <summary>
        /// 获取来源信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<SourceModel> GetById(Guid id)
        {
            using (var souSvc = new SourcesService())
            {
                return (await souSvc.GetOne(id)).MapTo<SourceModel>();
            }
        }

        /// <summary>
        /// 变更来源
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static async Task<bool> Update(SourceModel model)
        {
            using (var souSvc = new SourcesService())
            {
                var oldModel = await souSvc.GetOne(model.Id);
                if (oldModel == null)
                {
                    return false;
                }
                oldModel.SourceName = model.SourceName ?? oldModel.SourceName;
                await souSvc.EditAsvnc(oldModel);
            }
            return true;
        }
    }
}
